package com.xiaoyu.base.remoteconfig;

import com.xiaoyu.base.config.HttpConfig;
import com.xiaoyu.base.data.CacheData;
import com.xiaoyu.base.event.remoteconfig.RemoteConfigUpdateEvent;
import com.xiaoyu.net.request.RequestWithJsonDataReturn;
import com.xiaoyu.base.remoteconfig.base.ConfigValueUpdater;

import in.srain.cube.cache.DiskCacheProvider;
import in.srain.cube.request.FailData;
import in.srain.cube.request.JsonData;
import in.srain.cube.request.RequestData;
import in.srain.cube.request.RequestDefaultHandler;
import in.srain.cube.util.CLog;

public class ConfigLoader {

    private static final String TAG = "ConfigLoader";
    private static final String CACHE_KEY = "app-remote-config";

    private final ConfigValueUpdater mConfigValueUpdater;
    private volatile boolean mRequesting;

    ConfigLoader(ConfigValueUpdater configValueUpdater) {
        this.mConfigValueUpdater = configValueUpdater;
    }

    public boolean isRequesting() {
        return mRequesting;
    }

    void readFromRemote() {
        if (mRequesting) {
            return;
        }
        mRequesting = true;

        final RequestWithJsonDataReturn<JsonData> request = new RequestWithJsonDataReturn<>();
        final RequestData requestData = request.getRequestData();
        requestData.setRequestUrl(HttpConfig.UTIL_GET_REMOTE_CONFIG);
        request.setRequestHandler(new RequestDefaultHandler<JsonData, JsonData>() {
            @Override
            public JsonData processOriginData(JsonData originData) {
                JsonData jsonData = originData.optJson("data");
                update(jsonData);
                writeToLocal(jsonData);
                return originData;
            }

            @Override
            public void onRequestFinish(JsonData data) {
                mRequesting = false;
            }

            @Override
            public void onRequestFail(FailData failData) {
                super.onRequestFail(failData);
                mRequesting = false;
            }
        });
        request.enqueue();
    }

    void readFromLocal() {
        final DiskCacheProvider diskCacheProvider = CacheData.getInstance().getDiskCacheProvider();
        String cacheDataStr = diskCacheProvider.read(CACHE_KEY);
        JsonData jsonData = JsonData.create(cacheDataStr);
        CLog.d(TAG, "readFromLocal: %s", jsonData);
        update(jsonData);
    }

    private void update(JsonData jsonData) {
        mConfigValueUpdater.update(jsonData, () -> new RemoteConfigUpdateEvent().post());
    }

    private void writeToLocal(JsonData jsonData) {
        final DiskCacheProvider diskCacheProvider = CacheData.getInstance().getDiskCacheProvider();
        diskCacheProvider.write(CACHE_KEY, jsonData.toString());
        diskCacheProvider.flushDiskCacheAsync();
        CLog.d(TAG, "writeToLocal: %s", jsonData);
    }
}
